<template>
    <div>
        <el-container>
            <el-header>
                <el-menu class="el-menu-demo" mode="horizontal" background-color="#545c64" text-color="#fff"
                    active-text-color="#ffd04b">
                    <el-menu-item index="1"  @click="toAdmin">管理界面</el-menu-item>
                    <el-sub-menu index="4">
                        <template #title>
                            <el-icon>
                                <setting />
                            </el-icon>
                        </template>
                        <el-menu-item index="4-1" @click="dialogVisible = true">修改密码</el-menu-item>
                        <el-menu-item index="4-2" @click="exitLogin">退出登录</el-menu-item>
                    </el-sub-menu>
                </el-menu>
            </el-header>
            <el-main>
                <RouterView></RouterView>
            </el-main>
        </el-container>
    </div>

    <!-- 修改密码表单 -->
    <el-dialog v-model="dialogVisible" title="修改密码" width="500" draggable>
        <el-form ref="ruleFormRef" style="max-width: 400px" :model="ruleForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" :size="formSize" status-icon>
            <el-form-item label="账号" prop="username" >
                <el-input v-model="ruleForm.username" placeholder="请输入账号" clearable/>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="ruleForm.newPassword"  type="password" placeholder="请输入账号" clearable  show-password/>
            </el-form-item>
            <el-form-item label="再次输入新密码" prop="passwordCheck">
                <el-input v-model="ruleForm.passwordCheck" type="password" placeholder="请输入账号" clearable  show-password/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="confirmPassword">确定</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { RouterView, useRouter } from 'vue-router'
import { Menu as IconMenu, ChatDotRound, Setting } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import type { ComponentSize, FormRules } from 'element-plus'
import axios from '@/utils/request';
import { adminAccount } from '@/store'
import { removeToken } from '@/utils/auth';
const accountStore = adminAccount()
const router = useRouter()
const dialogVisible = ref(false)
const formSize = ref<ComponentSize>('default')
const ruleForm = reactive({
    username: '',
    newPassword: '',
    passwordCheck: ''
})
const rules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
    ],
    newPassword: [
        { min: 6, message: '密码长度必须大于六', trigger: 'blur' },
        { required: true, message: '请输入新密码', trigger: 'blur' },
    ],
    passwordCheck: [
        { min: 6, message: '密码长度必须大于六', trigger: 'blur' },
        { required: true, message: '请输入新密码', trigger: 'blur' },
    ]
})
onMounted(()=>{
    router.push('/menu')
    getAccountMsg()
})
function toAdmin() {
    router.push('/menu')
}
function exitLogin() {
    router.push('/adminLogin')
    removeToken();
}
const confirmPassword = async () => {
    // 首先检查新密码和密码确认字段是否有值，只有都有值时才进行后续修改密码的操作
    //两次密码不一致，提示用户两次密码不一致，直接结束方法
    if (ruleForm.newPassword !== ruleForm.passwordCheck) {
        ElMessage.error('两次密码不一致');
        return;
    }
    //两次密码一致且不为空，执行后续操作
    if (ruleForm.newPassword && ruleForm.passwordCheck) {
        try {
            // 发送PUT请求到后端接口，传递用户名和新密码信息，尝试更新密码
            const result = await axios.put("/admin", {
                username: ruleForm.username,
                password: ruleForm.newPassword,
            });
            // 根据后端返回的结果中的code值来判断修改密码操作是否成功
            if (result.data.code === 1) {
                // 如果code为1，表示修改成功，显示成功提示信息
                ElMessage.success('修改成功');
                // 关闭对话框，结束密码修改的交互流程
                dialogVisible.value = false;
            } else {
                // 如果code不为1，表示修改失败，提示用户检查账号和密码是否正确
                ElMessage.error('修改失败，请检查账号和密码是否正确');
            }
        } catch (error) {
            // 如果在发送请求或者接收响应过程中出现错误，例如网络问题、接口异常等，捕获该错误并显示通用的错误提示信息
            ElMessage.error('修改密码请求出错，请检查网络或联系后台管理员');
            console.error('修改密码出错:', error);
        }
    } else {
        // 如果新密码或者密码确认字段为空，提示用户密码不能为空
        ElMessage.error('密码不能为空');
    }
};
//获取管理员信息的方法
const getAccountMsg = async ()=>{
    try{
    const result = await axios.get('/admin?account='+accountStore.$state.account)
    if(result.data.code === 1){
        ruleForm.username = result.data.data.username
        ElMessage.success('登录成功')
    }else{}
}catch(error){}
}
//监听下线操作
onMounted(()=>{
    window.addEventListener('beforeunload',()=>{
        //去除请求头
        removeToken()
    })
    document.addEventListener('visibilitychange',()=>{
        if(document.visibilityState === 'hidden'){
            //去除请求头
            removeToken()
        }
    })
})
</script>

<style>
:blank {
    background-color: azure;
}
.button-center{
    align-items: center;
    text-align: center;
    justify-content: center;
}
</style>